<?php
namespace app\api\controller\deerhome\user;

use app\api\controller\deerhome\user\BaseAuth;
use app\admin\model\deerhome\Card as CardModel;
use app\admin\model\deerhome\CardOrder as CardOrderModel;
use app\admin\model\deerhome\CardOrderItems as CardOrderItemsModel;
use app\admin\model\deerhome\Order as OrderModel;
use app\admin\model\deerhome\OrderLog as OrderLogModel;
use app\admin\model\deerhome\OrderPayLog as OrderPayLogModel;
use app\admin\model\deerhome\UserAddress as UserAddressModel;
use think\Db;
use think\Exception;
use think\PDOException;

/**
 * 套餐次卡订单相关
 */
class CardOrder extends BaseAuth
{
    /**
     * 创建订单
    */
    public function create()
    {
        $id=$this->request->param("id",0,"intval");
        $data=(new CardModel)->with('cardItems')->where("status",1)->where("id",$id)->find();
        if(!$data){
            $this->err("套餐不存在");
        }
   
        $create=[];
        $create["deerhome_card_id"]=$id;
        $create["deerhome_card_name"]=$data['name'];
        $create["deerhome_user_id"]=$this->_user["id"];
        $create["sn"]=date('ymd').str_pad($this->_user['id'],8,"0",STR_PAD_LEFT).rand(100000,999999);
        $create["price"]=$data["price"];
        $create["price_yh"]=0;
        //判断是否是会员折扣
        if($this->_user['user_lev_id']>0 && $data['vip_discount']==1){
            $discount=Db::name("deerhome_user_lev")->where("id",$this->_user['user_lev_id'])->value("discount");
            if($discount){
                $discount=1-bcdiv($discount,100,2);
                $create['price_yh']=bcmul($data['price'],$discount,2);
                $create['price_yh_note']='会员折扣';
            }
        }
        $create["time_area"]=$data["time_area"];
        $create["price_need_pay"]=bcsub($create["price"],$create["price_yh"],2);

        //计算分销
        $create['agent_lev1_percent']=0;
        $create['agent_lev2_percent']=0;
        $fx=[];
        try{
            $fx=\Tools\AgentOrder::res($data,$this->_user);
        }catch(\Exception $e){
            $this->err($e->getMessage());
        }
        if(count($fx)>0){
            $create=array_merge($create,$fx);
        }

        $payLog=[
            'type'=>3,
            'deerhome_user_id'=>$this->_user['id'],
            'order_sn'=>$create['sn'],
            'price'=>$create['price_need_pay'],
            'add_time'=>date("Y-m-d H:i:s"),
            'payway_type'=>1
        ];
        $items=[];
        foreach($data["card_items"] as $v){
            $items[]=[
                "deerhome_items_id"=>$v["items_id"],
                "deerhome_items_name"=>$v["items_name"],
                "deerhome_items_gg_hash"=>$v["deerhome_items_gg_hash"],
                "gg_name"=>$v["items_gg_name"],
                "gg_price"=>$v["items_gg_price"],
                "gg_dw"=>$v["items_gg_dw"],
                "price"=>$v["price"],
                "num_left"=>0,
                "num"=>$v["num"]
            ];
        }
        $orderId=0;
        Db::startTrans();
        try{
            $order=CardOrderModel::create($create);
            $orderId=$order->id;
            OrderPayLogModel::create($payLog);
            foreach($items as &$v){
                $v["deerhome_card_order_id"]=$order->id;
            }
            (new CardOrderItemsModel)->saveAll($items);
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            $this->err($e->getMessage());
        }
        $create["orderId"]=$orderId;
        $this->ok($create);
    }
    /**
     * 拉取支付界面信息
    */
    public function order_pay_info()
    {
        $id=$this->request->param("id",0,"intval");
        $order=CardOrderModel::where("id",$id)->where("status",1)->where("deerhome_user_id",$this->_user["id"])->find();
        if(!$order){
            $this->err("待支付的订单不存在");
        }
        $data=[];
        $data['price']=bcsub($order['price_need_pay'],$order['price_payed'],2);
        $data['wallet']=$this->_user['wallet_charge'];
        $data['can']=bccomp($data['wallet'],$data['price'],2)>0?1:0;
        $this->ok($data);
    }
    /**
     * 我的次卡订单
    */
    public function my()
    {
        $cate=$this->request->param("cate",0,"intval");
        $where=[];
        $where["card_order.deerhome_user_id"]=$this->_user["id"];
        if($cate==0){
            $where["card_order.status"]=2;
        }else{
            $where["card_order.status"]=3;
        }
        $order=CardOrderModel::with(['card'])->where($where)->order('card_order.id desc')->paginate(10);
        $this->ok($order);
    }
    /**
     * 订单详情
    */
    public function detail()
    {
        $id=$this->request->param("id",0,"intval");
        $where=[];
        $where["id"]=["=",$id];
        $where["deerhome_user_id"]=["=",$this->_user["id"]];
        $order=CardOrderModel::with(['orderItems'])->where($where)->find();
        if(!$order){
            $this->err("订单不存在");
        }
        $this->ok($order);
    }
    /**
     * 下单界面信息
    */
    public function add_info()
    {
        $id=$this->request->param("id",0,"intval");
        $where=[];
        $where["card_order_items.id"]=["=",$id];
        $orderItems=CardOrderItemsModel::with(['items','cardOrder'])->where($where)->find()->toArray();
        if(!$orderItems){
            $this->err("该次卡已不可用");
        }
        if($orderItems['card_order']['deerhome_user_id']!=$this->_user["id"]){
            $this->err("该次卡已不可用");
        }
        if($orderItems['card_order']['status']!=2){
            $this->err("该次卡已不可用");
        }
        if($orderItems['num_left']<=0){
            $this->err("次卡内该产品已用完");
        }
        //检查是否过期
        if($orderItems['card_order']['end_time']<date("Y-m-d H:i:s")){
            $this->err("该次卡已过期");
        }
        $orderItems['address']=UserAddressModel::where("user_id",$this->_user['id'])->order("is_default desc")->find();
        if(!$orderItems['address']){
            $orderItems['address']['id']=0;
        }
        $this->ok($orderItems);
    }
    /**
     * 预约服务
    */
    public function creat_service()
    {
        $card_order_items_id=$this->request->param("id",0,'intval');
        $address=$this->request->param("address",0,'intval');
        $gg_id=$this->request->param("gg_id","",'trim');
        $num=$this->request->param("num",1,'intval');
        $day=$this->request->param("day",'');
        $time=$this->request->param("time",'');
        $note=$this->request->param("note","","trim");
        $imgs=$this->request->param("imgs/a",[]);

        if(!preg_match("/^\d{4}-\d{2}-\d{2}$/",$day)){
            $this->err("请选择日期");
        }
        if(!preg_match("/^\d{2}:\d{2}$/",$time)){
            $this->err("请选择时间");
        }
        if(($day." ".$time.":00") <date("Y-m-d H:i:s")){
            $this->err("已过去的时间不可选择");
        }
        $addressData=UserAddressModel::where("user_id",$this->_user['id'])->where("id",$address)->find();
        if(!$addressData){
            $this->err("地址不存在");
        }
        $where=[];
        $where["card_order_items.id"]=["=",$card_order_items_id];
        $orderItems=CardOrderItemsModel::with(['items','cardOrder'])->where($where)->find();
        if(!$orderItems){
            $this->err("该次卡已不可用");
        }
        if($orderItems['card_order']['deerhome_user_id']!=$this->_user["id"]){
            $this->err("该次卡已不可用");
        }
        if($orderItems['card_order']['status']!=2){
            $this->err("该次卡已不可用");
        }
        if($orderItems['num_left']<=0){
            $this->err("次卡内该产品已用完");
        }
        if($num<=0){
            $this->err("请选择数量");
        }
        if($num>$orderItems['num_left']){
            $this->err("次卡内该产品剩余次数不足");
        }
        //检查是否过期
        if($orderItems['card_order']['end_time']<date("Y-m-d H:i:s")){
            $this->err("该次卡已过期");
        }

        $priceItem=bcmul($orderItems['price'],$num,2);

        $add=[];
        if(count($imgs)>0){
            $add['imgs']=implode(",",$imgs);
        }
        $add['status']=2;
        $add['is_card']=1;
        $add['card_order_id']=$orderItems['card_order']['id'];
        $add['jz_user_id']=$this->_user['id'];
        //用户id补全成6位，根据用户id生成20位唯一订单号
        $add['sn']= date('ymd').str_pad($this->_user['id'],8,"0",STR_PAD_LEFT).rand(100000,999999);
        $add['price_light']=0;
        $add['price_item_total']=$priceItem;
        $add['price_total']=bcadd($add['price_light'],$priceItem,2);
        $add['price_yh']=0;
        $add['price_need_pay']=bcsub($add['price_total'],$add['price_yh'],2);
        $add['price_discount']=$add['price_total'];
        $add['time_add']=date("Y-m-d H:i:s");
        $add['user_name']=$addressData['user_name'];
        $add['user_phone']=$addressData['user_phone'];
        $add['address_detail']=$addressData['detail_address'];
        $add['address_title']=$addressData['address_title'];
        $add['address_address']=$addressData['address'];
        $add['latitude']=$addressData['latitude'];
        $add['longitude']=$addressData['longitude'];
        $add['note']=$note;
        $add['jz_items_id']=$orderItems['deerhome_items_id'];
        $add['gg_id']=$orderItems['deerhome_items_gg_hash'];
        $add['item_name']=$orderItems['deerhome_items_name'];
        $add['item_gg_name']=$orderItems['gg_name']."/".$orderItems['gg_dw'];
        $add['num']=$num;
        $add['date_day']=$day;
        $add['date_time']=$time;
        $add['price_pre_fc']=\bcmul($add['price_need_pay'],$orderItems['items']['worker_fc_bl']/100,2);
        $add['price_payed']=$add['price_need_pay'];

        $orderLog=[
            'add_time'=>date("Y-m-d H:i:s"),
            'ac_user'=>'用户',
            'note'=>"使用次卡支付成功，等待派单"
        ];
        $payLog=[
            'deerhome_user_id'=>$this->_user['id'],
            'type'=>1,
            'status'=>2,
            'is_card'=>1,
            'order_sn'=>$add['sn'],
            'price'=>$add['price_need_pay']*-1,
            'payway_type'=>1,
            'pay_way'=>'次卡支付',
            'note'=>"订单{$add['sn']}",
            'pay_time'=>date("Y-m-d H:i:s"),
            'add_time'=>date("Y-m-d H:i:s")
        ];

        

        Db::startTrans();
        try{
            $orderAdd=OrderModel::create($add);
            $orderLog['order_id']=$orderAdd->id;
            OrderLogModel::create($orderLog);
            OrderPayLogModel::create($payLog);
            //更新剩余次数
            CardOrderItemsModel::where("id",$card_order_items_id)->setDec("num_left",$num);
            //次卡订单是否结束
            $cardOrderUpdate=[];
            $cardOrderUpdate['num_left']=$orderItems['card_order']['num_left']-$num;
            if($cardOrderUpdate['num_left']<=0){
                $cardOrderUpdate['num_left']=0;
                $cardOrderUpdate['status']=3;
                $cardOrderUpdate['end_time']=date("Y-m-d H:i:s");
                $cardOrderUpdate['done_time']=date("Y-m-d H:i:s");
            }
            CardOrderModel::where("id",$orderItems['card_order']['id'])->update($cardOrderUpdate);
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            $this->err($e->getMessage());
        }
        $this->ok();
    }
    
}
